package com.yuanwu.ncs.service;


import io.etcd.jetcd.ByteSequence;
import io.etcd.jetcd.Client;
import io.etcd.jetcd.KeyValue;
import io.etcd.jetcd.kv.GetResponse;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class EtcdService {
    @Autowired
    private Client etcdClient;

    @SneakyThrows
    public String get(String key) {
        ByteSequence byteKey = ByteSequence.from(key, StandardCharsets.UTF_8);
        GetResponse response = etcdClient.getKVClient().get(byteKey).get();
        List<KeyValue> values = response.getKvs();
        if (!values.isEmpty()) {
            return values.get(0).getValue().toString(StandardCharsets.UTF_8);
        }
        return null;
    }

    @SneakyThrows
    public void put(String key, String value) {
        ByteSequence byteKey = ByteSequence.from(key, StandardCharsets.UTF_8);
        ByteSequence byteValue = ByteSequence.from(value, StandardCharsets.UTF_8);
        etcdClient.getKVClient().put(byteKey, byteValue).get();
    }

    @SneakyThrows
    public void delete(String key) {
        ByteSequence byteKey = ByteSequence.from(key, StandardCharsets.UTF_8);
        etcdClient.getKVClient().delete(byteKey).get();
    }
}
